package com.huangtang.pc.serializer;

import com.alibaba.fastjson2.JSON;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
 
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * 自定义序列化和反序列化
 * @param <T>
 * @author sunjf
 * @date 2024/1/10
 */
public class FastJson2JsonRedisSerializer<T> implements RedisSerializer<T> {
 
    public static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;
 
    private final Class<T> clazz;
 
    public FastJson2JsonRedisSerializer(Class<T> clazz) {
        super();
        this.clazz = clazz;
    }

    /**
     * 设置序列化方式
     * @param t 参数
     * @return 序列化后的字符串
     * @throws SerializationException 序列化异常
     */
    @Override
    public byte[] serialize(T t) throws SerializationException {
        if (t == null) {
            return new byte[0];
        }
        return JSON.toJSONString(t).getBytes(DEFAULT_CHARSET);
    }

    /**
     * 设置反序列化方式
     * @param bytes 字符数据
     * @return 反序列化后的对象
     * @throws SerializationException 序列化异常
     */
    @Override
    public T deserialize(byte[] bytes) throws SerializationException {
        if (bytes == null || bytes.length == 0) {
            return null;
        }
        String str = new String(bytes, DEFAULT_CHARSET);
 
        return JSON.parseObject(str, clazz);
    }
}